<?php


namespace app\admin\controller\mall;


use app\api\model\mysql\MallAccountLog;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallSetting;
use app\api\model\mysql\MallUser;
use app\api\model\mysql\MallUserAddress;
use app\api\model\mysql\MallUserPaylog;
use app\common\controller\AdminController;
use app\common\lib\ArrClass;
use app\common\lib\Sign;
use app\common\lib\Str;
use app\common\model\MallCommissionLevel;
use think\App;
use think\Model;

class Order extends AdminController
{
    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallOrder();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where, $where1) = $this->buildTableParames2();
            $count = $this->model
                ->alias('o')
                ->field('o.*,og.goods_name,u.nickName as nick,mu.nickName')
                ->join('mall_order_goods og','og.order_id=o.id')
                ->join('mall_user u','u.openid=o.openid')
                ->join('mall_user mu','mu.id=u.parent_id','left')
                ->where($where)
                ->where($where1)
                ->group('o.id')
                ->count();

            $list = $this->model
                ->alias('o')
                ->field('o.*,og.goods_name,u.nickName as nick,mu.nickName')
                ->join('mall_order_goods og','og.order_id=o.id')
                ->join('mall_user u','u.openid=o.openid')
                ->join('mall_user mu','mu.id=u.parent_id','left')
                ->where($where)
                ->where($where1)
                ->page($page, $limit)
                ->order('o.id desc')
                ->group('o.id')
                ->select();
            foreach ($list as $k=>$v){
                $paylog =(new MallUserPaylog())->where("order_id='".$v['id']."' and status=1")->find();
                if($paylog){
                    $list[$k]['partnerno'] =$paylog['ordersn'];
                }else{
                    $list[$k]['partnerno'] ='--';
                }
                $count1 =(new MallOrderGoods())->where("order_id='".$v['id']."'")->sum('total');

                $list[$k]['goodscount'] =$count1;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    public function edit($id){
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            switch($post['orderToStatus']){
                case 1: //确认付款
                    $post['orderstatus'] =1;
                    $post['paytime'] =time();
                    break;
                case 2: //确认发货
                    if(!$post['express'] || !$post['expresscom'] || !$post['expresssn']){
                        $this->error('发货信息请填写完整');
                    }
                    $post['orderstatus'] =2;
                    $post['shipping_time'] =time();
                    break;
                case 3: //确认收货
                    $post['orderstatus'] =3;
                    $post['confirm_time'] =time();
                    break;
                case 4: //已完成

                    break;
                default:
                    break;
            }
            $goodslist =(new MallOrderGoods())->where("order_id",'=',$id)->select()->toArray();
            $this->model->startTrans();
            try {
                $save = $row->save($post);
                // 发送打印请求
                if($post['orderToStatus']==1){
                    $setting =(new MallSetting())->where("name='isopenid'")->find();
                    if($setting && $setting['option_value']==1) {
                        $guid = Str::guid();
                        $content = "<FS2><center>**#1 荐贝康**</center></FS2>";
                        $content .= str_repeat('.', 32);
                        $content .= "<FS2><center>--在线支付--</center></FS2>";
                        $content .= "<FS><center>荐贝康小程序商城</center></FS>";
                        $content .= "订单时间:" . $row['create_time'] . "\n";
                        $content .= "订单编号:" . $row['ordersn'] . "\n";
                        $content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
                        $content .= "<table>";
                        $content .= "<tr><td>名称</td><td>数量</td><td>单价</td></tr>";
                        foreach ($goodslist as $k => $v) {

                            $content .= "<tr><td>" . $v['goods_name'] . "</td><td>x" . $v['total'] . "</td><td>" . $v['price'] . "</td></tr>";
                        }
                        $content .= "</table>";
                        $content .= str_repeat('.', 32);
                        $content .= "小计:￥" . $row['orderprice'] . "\n";
                        $content .= "折扣:￥" . $row['discountprice'] . " \n";
                        $content .= str_repeat('*', 32);
                        $content .= "订单总价:￥" . $row['payprice'] . " \n";
                        $content .= str_repeat('*', 32);
                        $content .= "收货人:" . $row['realname'] . " \n";
                        $content .= "收货地址:" . $row['address'] . " \n";
                        $content .= "收货人电话:" . $row['mobile'] . " \n";
                        $content .= "<FS2><center>**#1 完**</center></FS2>";
                        $senddata = array(
                            'machineCode' => '4004701676',
                            'content' => $content,
                            'type' => 1,
                            'id' => $guid
                        );
                        Sign::getInstance()->__post($senddata, 'print/printer');
                    }
                }
                if($post['orderToStatus'] == 3){
                    $order =$this->model->find($id);
                    if($order['isyes'] ==0){
                        // 付款完成，返利以及分销商升级
                        $member = (new MallUser())->getUserByList($order['openid'],'id,openid,nickName,commission_level,parent_id');
                        $levels =(new MallCommissionLevel())->getLevels();
                        foreach ($levels as $k=>$v){
                            // 满足购买商品金额进行升级
                            if($v['ordermoney'] <= $order['payprice'] && $v['id']>$member['commission_level']){
                                (new MallUser())->where("id",$member['id'])->save(array('commission_level'=>$v['id'],'level_time'=>time()));
                            }
                        }
                        if($member['parent_id'] >0){
                            $parentmember = (new MallUser())->getUserById($member['parent_id'],'id,openid,nickName,commission_level');
                            $levelinfo =(new MallCommissionLevel())->getlevelInfo($parentmember['commission_level']);

                            $count=$this->model->getOrderByCount([['orderstatus','in',[3,4]],['openid','=',$member['openid']]]);
                            if($count==1){ //首单
                                if($order['commission']>0){
                                    (new MallAccountLog())->saveAccoutLog($id,$parentmember['openid'],$order['commission'],3,'推荐返利');
                                }
                            }
                            if($order['againprice']>0){
                                (new MallAccountLog())->saveAccoutLog($id,$parentmember['openid'],$order['againprice'],4,'复购返利');

                                // 存在复购奖励，计算团队奖励给推荐人。
                                $set=(new MallSetting())->getSettingInfo('teamset');
                                $teamlprice =round($order['againprice']*$set['option_value']/100,2);
                                if($teamlprice>0){
                                    (new MallAccountLog())->saveAccoutLog($id,$parentmember['openid'],$teamlprice,5,'团队奖励');
                                }
                            }
                            $row->save(array('isget'=>1)); // 首单返佣入账
                            // 下级会员数满足条件 升级等级
                            $memcount =(new MallUser())->getMemCount($member['parent_id']);
                            if($levelinfo['membercount']<=$memcount && $levelinfo['membercount']>0 && $parentmember['commission_level']<5){
                                (new MallUser())->where("id",$member['parent_id'])->inc('commission_level',1)->update();
                                (new MallUser())->where("id",$member['parent_id'])->save(array('level_time'=>time()));
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            $this->model->commit();
            $this->success('保存成功');
        }
        switch ($row['orderstatus']){
            case 0:
                $row['statusname'] ='待付款';
                break;
            case 1:
                $row['statusname'] ='待发货';
                break;
            case 2:
                $row['statusname'] ='待收货';
                break;
            case 3:
                $row['statusname'] ='已完成';
                break;
            case 4:
                $row['statusname'] ='售后/退款';
                break;
            default:
                $row['statusname'] ='已取消';
                break;
        }
        $userinfo =(new MallUser())->getUserByList($row['openid'],'nickName');
        $row['nickName'] =$userinfo['nickName'];
        $goodslist=(new MallOrderGoods())->getByOrderGoodsList($id);
        //$addinfo =(new MallUserAddress())->where([['id','=',$row['address_id']]])->find();
        $row['cityarea'] ='';
        $this->assign('row', $row);
        $this->assign('goodslist', $goodslist);
        return $this->fetch();
    }


}